package com.study.leetcode;
//https://leetcode.cn/problems/minimum-falling-path-sum/
public class Solution_931 {
    public static int minFallingPathSum(int[][] matrix) {
        int min = Integer.MAX_VALUE;
        int rows = matrix.length;
        int cols = matrix[0].length;
        int a, b, c;
        for (int i = 1; i < rows; i++) {
            //斜右
            b = Integer.MAX_VALUE;
            //斜左
            c = Integer.MAX_VALUE;
            for (int j = 0; j < cols; j++) {
                a = matrix[i - 1][j] + matrix[i][j];
                if (j + 1 < cols) {
                    b = matrix[i - 1][j + 1] + matrix[i][j];
                }
                if (j - 1 >= 0) {
                    c = matrix[i - 1][j - 1] + matrix[i][j];
                }
                matrix[i][j] = Math.min(a, Math.min(b, c));
            }
        }
        int lastRow = rows - 1;
        for (int i = 0; i < cols; i++) {
            min = Math.min(min, matrix[lastRow][i]);
        }
        return min;
    }

    public static void main(String[] args) {
        int[][] matrix = {
                {-19, 57},
                {-40, 5},
        };
        System.out.println("minFallingPathSum(matrix) = " + minFallingPathSum(matrix));

    }
}
